﻿// 2024/5/20: 首个版本

using System;
using System.Collections.Generic;
using System.Linq;
using ASEva;
using ASEva.Samples;
using ASEva.UIEto;
using Eto.Forms;
using Eto.Drawing;

namespace CommonSource
{
    class BusMessageAdder : DialogPanel
    {
        public BusMessageAdder(List<String> addedBusMessageIDs, SelectBusMessageHandler handler, Icon icon = null)
        {
            this.addedBusMessageIDs = addedBusMessageIDs;
            this.handler = handler;

            Icon = icon;
            Title = chinese ? "总线报文添加" : "Add bus message";
            SetFixMode(440, 570, true);

            var mainLayout = this.SetContentAsColumnLayout();
            var searchBox = mainLayout.AddControl(new SearchBox()) as SearchBox;
            treeView = mainLayout.AddControl(new SimpleTreeView(), true) as SimpleTreeView;
            var buttonLayout = mainLayout.AddRowLayout();
            buttonLayout.AddSpace();
            buttonAdd = buttonLayout.AddButton(chinese ? "添加" : "Add", false, 100);

            buttonAdd.Enabled = false;

            noAvailables = !rebuildTreeView(Agency.GetSignalTree(), "");
            if (noAvailables)
            {
                searchBox.Enabled = false;
                addNoAvailables();
            }

            searchBox.TextChanged += delegate
            {
                noAvailables = !rebuildTreeView(Agency.GetSignalTree(), searchBox.Text.ToLower());
                if (noAvailables)
                {
                    buttonAdd.Enabled = false;
                    addNoAvailables();
                }
            };

            buttonAdd.Click += delegate
            {
                addBusMessage();
            };

            treeView.SelectedItemChanged += delegate
            {
                if (noAvailables) return;

                bool enabled = false;
                var key = treeView.GetSelectedKey();
                if (key != null && key is SignalTreeNode)
                {
                    var nodeType = (key as SignalTreeNode).Type;
                    enabled = (int)nodeType == (int)SignalTreeNodeType.BusMessage;
                }
                buttonAdd.Enabled = enabled && !addedBusMessageIDs.Contains((key as SignalTreeNode).ID) && !addButtonDisabled;
            };

            treeView.SelectedItemActivated += delegate
            {
                if (buttonAdd.Enabled)
                {
                    addBusMessage();
                }
            };
        }

        private bool rebuildTreeView(SignalTreeNode[] tops, String key)
        {
            var topNodes = new List<SimpleTreeNode>();
            var itemAdded = false;
            bool keyValid = key.Length >= 2;

            foreach (var top in tops)
            {
                if (top.Type != SignalTreeNodeType.BusProtocol) continue;
                
                var topMatch = keyValid && top.Name.ToLower().Contains(key);

                var topNode = new SimpleTreeNode{ Key = top, Text = top.Name };
                var shouldAddTopNode = !keyValid || topMatch;

                foreach (var middle in top.Children)
                {
                    var middleMatch = keyValid && (middle.ID.ToLower().Contains(key) || middle.Name.ToLower().Contains(key));
                    var isAdded = (int)middle.Type == (int)SignalTreeNodeType.BusMessage && addedBusMessageIDs.Contains(middle.ID);

                    var middleNode = new SimpleTreeNode{ Key = middle, Text = middle.Name, TextColor = isAdded ? Colors.Green : Colors.Blue };
                    bool shouldAddMiddleNode = !keyValid || topMatch || middleMatch;

                    if (shouldAddMiddleNode)
                    {
                        if (keyValid) middleNode.ChildNodesExpanded = true;
                        topNode.ChildNodes.Add(middleNode);
                        shouldAddTopNode = true;
                    }
                }

                if (shouldAddTopNode)
                {
                    if (keyValid) topNode.ChildNodesExpanded = true;
                    topNodes.Add(topNode);
                    itemAdded = true;
                }
            }

            treeView.SetModel(topNodes.ToArray(), true);

            return itemAdded;
        }

        private void addNoAvailables()
        {
            var topNode = new SimpleTreeNode{ Key = new object(), Text = chinese ? "(无可用)" : "(No availables)" };
            treeView.SetModel(new SimpleTreeNode[]{ topNode }, false);
        }

        private void addBusMessage()
        {
            var key = treeView.GetSelectedKey();
            var busMessageID = (key as SignalTreeNode).ID;
            if (!handler.SelectBusMessage(busMessageID))
            {
                addButtonDisabled = true;
            }
            addedBusMessageIDs.Add(busMessageID);

            var updateTask = new SimpleTreeNodeUpdateTask();
            updateTask.Key = key;
            updateTask.TextColor = Colors.Green;
            treeView.UpdateNodes(new SimpleTreeNodeUpdateTask[]{ updateTask });

            buttonAdd.Enabled = false;
        }

        private List<String> addedBusMessageIDs;
        private SelectBusMessageHandler handler;
        private bool addButtonDisabled;
        private bool noAvailables;
        private SimpleTreeView treeView;
        private Button buttonAdd;

        private bool chinese = Agency.GetAppLanguage() == "ch";
    }
}
